import gnotifier_module
import gnotifier, pygtk, os, sys, gtk, gobject, webbrowser, re, httplib, xml.dom.minidom, time
APP_DIR = gnotifier.APP_DIR

class GReaderNotifier(gnotifier_module.GNmodule):
    statusicon = 'unread.png'
    service = 'reader'
    feedUri = 'https://www.google.com/reader/atom/user/-/state/com.google/reading-list'

    def delete_event(self, widget, event, data=None):
        print "delete event occurred"
        return False

    def destroy(self, widget, data=None):
        print "Bye!"
        gtk.main_quit()
    
    def _checkNewMail(self):
        i = 0
        fullCount = 0
        data_array = []      

        if (self.lastCheck == None):
            self.lastCheck = ''
        doc=xml.dom.minidom.parseString(self.gmailFeed.feed)

        fullCount = int(doc.getElementsByTagName("fullcount")[0].firstChild.nodeValue)
        print fullCount

        for entry in doc.getElementsByTagName("entry"):
            for issued in entry.getElementsByTagName("issued"):
                # Hack to use 00 hour instead of 24 for midnight                
                issued.firstChild.nodeValue = issued.firstChild.nodeValue.replace('T24', 'T00')
                print issued.firstChild.nodeValue +'>'+ self.lastCheck
                if (issued.firstChild.nodeValue >= self.lastCheck):
                    i = i + 1
                    node = {}
                    print 'New mail!'
                    for author in entry.getElementsByTagName("author"):
                        for name in author.getElementsByTagName("name"):                
                            name_str = name.firstChild.nodeValue
                            node['name'] = name_str
                    for title in entry.getElementsByTagName("title"):
                        title_str = title.firstChild.nodeValue
                        node['title'] = title_str
                    for summary in entry.getElementsByTagName("summary"):
                        try:                        
                            summary_str = summary.firstChild.nodeValue
                            node['summary'] = summary_str
                        except:
                            node['summary'] = ''
                    data_array.append(node)

                else:
                    break
        #main.pluginManager.executePluginAction('newMessagesReceived', [data_array, fullCount])
        self.pluginManager.executePluginAction('newMessagesReceived', [data_array, fullCount])
        self.lastCheck = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())      

        return i    

    def _generateMenu(self):
        print "generateMenu..."
        self.menu = gtk.Menu()

        self.labelItemRead = gtk.Label('No new messages')        
        self.menuItemRead = gtk.MenuItem()
        self.menuItemRead.add(self.labelItemRead)
        self.menu.append(self.menuItemRead)

        self.menuItemsCheckNow = gtk.MenuItem('Check Now')
        self.menuItemsCheckNow.connect("activate", self.getMail)
        self.menu.append(self.menuItemsCheckNow)

        self.separator = gtk.SeparatorMenuItem()
        self.menu.append(self.separator)

        self.menuInbox = gtk.MenuItem('Inbox')
        self.menuInbox.connect("activate", lambda w: webbrowser.open('http://mail.google.com/mail/?search=inbox&source=gnotifier-gtk&client=gnotifier-gtk&auth='+self.gmailFeed.token))
        self.menu.append(self.menuInbox)

        self.menuCompose = gtk.MenuItem('Compose')
        self.menuCompose.connect("activate", lambda w: webbrowser.open('http://mail.google.com/mail/?view=cm&tf=0&source=gnotifier&client=google-macgmailwidget&auth='+self.gmailFeed.token))
        self.menu.append(self.menuCompose)

        self.separator = gtk.SeparatorMenuItem()
        self.menu.append(self.separator)

        self.menuPreferences = gtk.MenuItem('Preferences...')
        self.menuPreferences.connect("activate", lambda w: self.loginInto())
        self.menu.append(self.menuPreferences)

        self.menuItem = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
        self.menuItem.connect("activate", lambda w: self.showPopup)
        self.menu.append(self.menuItem)

        self.separator = gtk.SeparatorMenuItem()
        self.menu.append(self.separator)

        self.menuItem = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        self.menuItem.connect("activate", self.destroy, self.icon)
        self.menu.append(self.menuItem) 

    def _populateMenu(self):
        i = 0;
        print "Populate menu..."
        #print self.gmailFeed.feed
        self.menuReadItems = gtk.Menu()

        doc=xml.dom.minidom.parseString(self.gmailFeed.feed)

        fullCount = int(doc.getElementsByTagName("fullcount")[0].firstChild.nodeValue)

        #doc =xml.dom.minidom.parseString('<a></a>')
        for entry in doc.getElementsByTagName("entry"):
            i = i + 1
            for author in entry.getElementsByTagName("author"):
                for name in author.getElementsByTagName("name"):                
                    name_str = name.firstChild.nodeValue
            for title in entry.getElementsByTagName("title"):
                title_str = title.firstChild.nodeValue
            for link in entry.getElementsByTagName("link"):
                link_str = link.getAttribute("href")
            self.menuItem = gtk.MenuItem(name_str+' - Subject: '+title_str, False)
            self.menuItem.connect("activate", self.openUrl, link_str+'&auth='+self.gmailFeed.token)
            self.menuReadItems.append(self.menuItem)
    
        if (fullCount > 20):           
            self.menuItemRead.set_submenu(self.menuReadItems)
            self.labelItemRead.set_label('+20 Unread From')
            self.menu.show()
        elif (fullCount == 0):
           self.labelItemRead.set_label('No new messages')
           self.menuItemRead.remove_submenu()
        else:
            self.menuItemRead.set_submenu(self.menuReadItems)
            self.labelItemRead.set_label('%i Unread From' % i)
            self.menu.show()

